﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using Microsoft.Phone.Net.NetworkInformation;
using Store.WP7.Data;
using Store.WP7.Data.WebStore;
using Store.WP7.Framework;
using Store.WP7.Framework.ErrorManagement;
using Store.WP7.Framework.Settings;

namespace Store.WP7.ViewModels
{
    public class ProductsViewModel : PageViewModelBase
    {
        #region Private Fields

        private StoreService _StoreService;

        #endregion

        #region Private Methods

        private void Initialize()
        {
            _StoreService = new StoreService();
            LoadProducts();
        }

        private void LoadProducts()
        {
            BusyMessage = "chargement des produits en cours";
            IsBusy = true;

            if (NetworkInterface.GetIsNetworkAvailable())
            {
                _StoreService.LoadProductsAsync(callback =>
                {
                    if (callback.Error == null)
                    {
                        var products = callback.Result;
                        CacheManager.Current.Add(AppSettingsKeyNames.ProductsPage, products, TimeSpan.FromMinutes(15));

                        Deployment.Current.Dispatcher.BeginInvoke(() => Products.Clear());

                        foreach (var p in products)
                        {
                            var viewModel = new ProductViewModel(p);
                            Deployment.Current.Dispatcher.BeginInvoke(() => {
                                Products.Add(viewModel);
                            });
                            System.Threading.Thread.Sleep(20);
                        }

                        StoreCache.Instance.UpdateProducts(products);

                        Deployment.Current.Dispatcher.BeginInvoke(() => {
                            IsBusy = false;
                        });
                    }
                    else
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() => {
                            IsBusy = false;
                            ErrorManager.HandleError(ErrorType.WebServiceCallbackFail, callback.Error);
                        });
                    }
                });
            }
            else
            {
                var productsPage = CacheManager.Current.Get<List<Product>>(AppSettingsKeyNames.ProductsPage);
                if (productsPage != null)
                {
                    Products.Clear();
                    foreach (var p in productsPage)
                    {
                        var viewModel = new ProductViewModel(p);
                        Products.Add(viewModel);
                        System.Threading.Thread.Sleep(20);
                    }

                    StoreCache.Instance.UpdateProducts(productsPage);

                    IsBusy = false;
                }
            }
        }

        #endregion

        #region Public Methods

        public void OnProductsSelectionChanged()
        {
            if (SelectedProduct != null)
            {
                NavigationService.Navigate(new System.Uri(string.Format("/Views/ProductDetailsView.xaml?productId={0}", SelectedProduct.Id), System.UriKind.Relative));
                // To unselect the item from the list
                SelectedProduct = null;
            }
        }

        public override void OnLoaded()
        {
            base.OnLoaded();

            Initialize();
        }

        #endregion

        #region Public Properties

        private readonly ObservableCollection<ProductViewModel> _products = new ObservableCollection<ProductViewModel>();

        /// <summary>
        /// Gets all products
        /// </summary>
        public ObservableCollection<ProductViewModel> Products
        {
            get
            {
                return _products;
            }
        }

        private ProductViewModel _selectedProduct;
        /// <summary>
        /// Selected product
        /// </summary>
        public ProductViewModel SelectedProduct
        {
            get { return _selectedProduct; }
            set
            {
                _selectedProduct = value;
                RaisePropertyChanged(() => SelectedProduct);

                OnProductsSelectionChanged();
            }
        }

        #endregion
    }
}
